package com.ucap.weking.guangan.httpTools;

import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by weking on 2017/10/18.
 */

public class HttpCallRequest {
    String uri;
    OnCallListener onCallListener;

    public HttpCallRequest(String uri, OnCallListener onCallListener) {
        this.uri = uri;
        this.onCallListener = onCallListener;
    }

    public static void callRequest(String uri, OnCallListener onCallListener) {
        HttpCallRequest callRequest = new HttpCallRequest(uri, onCallListener);
        callRequest.call();
    }

    public void call() {
        Log.i("DataUri", "call: " + uri);
        OkHttpClient httpClient = new OkHttpClient();
        Request builder = new Request.Builder().url(uri).build();
        Call call = httpClient.newCall(builder);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("DataUriRequestErr", "onResponse: " + e.getMessage());
                if (onCallListener != null)
                    onCallListener.onErr(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                Log.i("DataUriRequest", "onResponse: " + body);
                if (body != null && !body.isEmpty()) {
                    if (onCallListener != null)
                        onCallListener.onRequest(body);
                }
            }
        });
    }

    public interface OnCallListener {
        void onRequest(String body);
        void onErr(Exception e);
    }
}
